package com.xhwl.data.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Block;
import com.xhwl.common.pojo.cent.sdata.OrganizationType;
import com.xhwl.common.pojo.cent.sdata.SpaceFunctionType;
import com.xhwl.common.query.cent.sdata.BlockQuery;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.service.IBlockService;
import com.xhwl.data.service.IOrganizationTypeService;
import com.xhwl.data.service.ISpaceFunctionTypeService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: luyi
 * @Description: 地块
 * @Date: Create in 16:06 2021/7/16
 */
@RestController
public class BlockController {

    @Autowired
    private IBlockService blockService;

    private static final Logger log = LoggerFactory.getLogger(BuildingController.class);

    @Autowired
    private ISpaceFunctionTypeService spaceFunctionTypeService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    /**
     * 批量创建
     *
     * @param blocks
     * @return
     */
    @RequestMapping(value = "/block/batch-create")
    public ResultJson batchCreate(@RequestBody List<Block> blocks) {
        if (CollectionUtils.isEmpty(blocks)) {
            return ResultJson.success();
        }
        for (Block block : blocks) {
            if (StringUtils.isEmpty(block.getName()) || block.getName().length() > 32) {
                return ResultJson.fail("名称输入错误");
            }
            if (StringUtils.isNotEmpty(block.getCode()) && block.getCode().length() > 36) {
                return ResultJson.fail("编码输入错误");
            }
            if (null == block.getParentId() || block.getParentId().toString().length() > 11) {
                return ResultJson.fail("上级信息错误");
            }
            if (null != block.getArea() && block.getArea().toString().length() > 13) {
                return ResultJson.fail("建筑面积错误");
            }
            if (null != block.getPublicArea() && block.getPublicArea().toString().length() > 13) {
                return ResultJson.fail("公区面积错误");
            }
            if (null != block.getRentalArea() && block.getRentalArea().toString().length() > 13) {
                return ResultJson.fail("租赁面积错误");
            }
            if (StringUtils.isNotEmpty(block.getRemark()) && block.getRemark().length() > 250) {
                return ResultJson.fail("备注输入错误");
            }
        }
        return blockService.batchCreate(blocks);
    }

    /**
     * 创建更新
     *
     * @param block
     * @return
     */
    @RequestMapping(value = "/block/insert")
    public ResultJson create(@RequestBody Block block) {
        if (null == block) {
            return ResultJson.fail("参数错误");
        }
        if (StringUtils.isEmpty(block.getName()) || block.getName().length() > 32) {
            return ResultJson.fail("名称输入错误");
        }
        if (StringUtils.isNotEmpty(block.getCode()) && block.getCode().length() > 36) {
            return ResultJson.fail("编码输入错误");
        }
        if (null == block.getParentId() || block.getParentId().toString().length() > 11) {
            return ResultJson.fail("上级信息错误");
        }
        if (null != block.getArea() && block.getArea().toString().length() > 13) {
            return ResultJson.fail("建筑面积错误");
        }
        if (null != block.getPublicArea() && block.getPublicArea().toString().length() > 13) {
            return ResultJson.fail("公区面积错误");
        }
        if (null != block.getRentalArea() && block.getRentalArea().toString().length() > 13) {
            return ResultJson.fail("租赁面积错误");
        }
        if (StringUtils.isNotEmpty(block.getRemark()) && block.getRemark().length() > 250) {
            return ResultJson.fail("备注输入错误");
        }
        if (null != block.getId()) {
            return blockService.update(block);
        } else {
            if (null == block.getParentId()) {
                return ResultJson.fail("参数错误");
            }
            return blockService.create(block);
        }
    }

    /**
     * 列表查询
     *
     * @param blockQuery
     * @return
     */
    @RequestMapping(value = "/block/list")
    public ResultJson list(@RequestBody BlockQuery blockQuery) {
        List<Block> list = blockService.list(blockQuery);
        return ResultJson.success(list);
    }

    /**
     * 分页查询
     *
     * @param blockQuery
     * @param page
     * @return
     */
    @RequestMapping(value = "/block/page")
    public ResultJson page(@RequestBody BlockQuery blockQuery, Page page) {
        Page<Block> page1 = blockService.page(blockQuery, page);
        List<SpaceFunctionType> spaceFunctionTypes = this.listFunctionType();
        List<Block> records = page1.getRecords();
        records.forEach(x->processBean(x,spaceFunctionTypes,blockQuery.getTypeId()));
        page1.setRecords(records);
        return ResultJson.success(page1);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/block/delete")
    public ResultJson delete(Integer id) {
        return blockService.delete(id);
    }

    /**
     * 详情
     *
     * @param id
     * @param orgId
     * @return
     */
    @RequestMapping(value = "/block/detail")
    public ResultJson detail(Integer id, Integer orgId,Integer typeId) {
        QueryWrapper<Block> blockQueryWrapper = new QueryWrapper<>();
        if (null != id) {
            blockQueryWrapper.eq("id", id);
        } else if (null != orgId) {
            blockQueryWrapper.eq("organization_id", orgId);
        } else {
            return ResultJson.success();
        }
        Block one = blockService.getOne(blockQueryWrapper);
        if (null == one) {
            log.warn("地块数据不存在");
            return ResultJson.success();
        }
        List<SpaceFunctionType> spaceFunctionTypes = this.listFunctionType();
        processBean(one,spaceFunctionTypes,typeId);
        return ResultJson.success(one);
    }

    private Block processBean(Block block,List<SpaceFunctionType> spaceFunctionTypes,Integer typeId) {
        if(null != block.getFunctionType()){
            for (SpaceFunctionType spaceFunctionType : spaceFunctionTypes) {
                if(block.getFunctionType().equals(spaceFunctionType.getId())){
                    block.setFunctionName(spaceFunctionType.getName());
                }
            }
        }
        dealJson(block,typeId);
        return block;
    }

    /**
     * 兼容历史数据
     */
    private void dealJson (Block param,Integer typeId){
        if(typeId == null){
            return;
        }
        QueryWrapper<OrganizationType> organizationTypeQueryWrapper = new QueryWrapper<>();
        organizationTypeQueryWrapper.eq("id", typeId);
        OrganizationType organizationType = organizationTypeService.getOne(organizationTypeQueryWrapper);
        String source = organizationType.getSource();
        if(org.apache.commons.lang3.StringUtils.isEmpty(source)){
            return;
        }
        Map<String,Object> map = new HashMap<>();
        JSONObject sourceJson = JSON.parseObject(source);
        JSONArray fields = sourceJson.getJSONArray("fields");
        if(CollectionUtil.isNotEmpty(fields)) {
            for (int i = 0; i < fields.size(); i++) {
                JSONObject fieldJsonObject = fields.getJSONObject(i);
                fieldJsonObject.remove("__config__");
                String vModel = fieldJsonObject.getString("vModel");
                //兼容以前数据
                if ("name".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getName() != null ? param.getName() : "");
                    map.put("name",param.getName() != null ? param.getName() : "");
                } else if ("code".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getCode() != null ? param.getCode() : "");
                    map.put("code",param.getCode() != null ? param.getCode() : "");
                } else if ("area".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getArea() != null ? param.getArea() : "");
                    map.put("area",param.getArea() != null ? param.getArea() : "");
                } else if ("rentalArea".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getRentalArea() != null ? param.getRentalArea() : "");
                    map.put("rentalArea",param.getRentalArea() != null ? param.getRentalArea() : "");
                } else if ("publicArea".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getPublicArea() != null ? param.getPublicArea() : "");
                    map.put("publicArea",param.getPublicArea() != null ? param.getPublicArea() : "");
                } else if ("remark".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getRemark() != null ? param.getRemark() : "");
                    map.put("remark",param.getRemark() != null ? param.getRemark() : "");
                }else if ("sortField".equals(vModel)){
                    fields.getJSONObject(i).put("defaultValue",param.getSortField() != null ? param.getSortField() : "");
                    map.put("sortField",param.getSortField() != null ? param.getSortField() : "");
                }  else  {
                    if(param.getExpand() != null) {
                        JSONObject jsonObject = JSON.parseObject(param.getExpand());
                        if(jsonObject.get(vModel) != null) {
                            fields.getJSONObject(i).put("defaultValue", jsonObject.get(vModel));
                            map.put(vModel,jsonObject.get(vModel));
                        }else{
                            map.put(vModel,"");
                        }
                    }else{
                        map.put(vModel,"");
                    }
                }
            }
        }
        param.setExpand(JSON.toJSONString(sourceJson));
        param.setFullData(JSON.toJSONString(map));
    }

    private List<SpaceFunctionType> listFunctionType() {
        return spaceFunctionTypeService.list(new QueryWrapper<SpaceFunctionType>()
                .eq("org_type", OrganizationTypeEnum.BLOCK.getId()));
    }
}
